package com.zqx.util;



import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;


import java.io.IOException;
import java.text.DateFormat;


public class JsonUtil {

    private static final Logger LOG = LoggerFactory.getLogger(JsonUtil.class);
    private static final ObjectMapper mapper = new ObjectMapper();

    static {
        mapper.enable(SerializationFeature.WRITE_NULL_MAP_VALUES);
        mapper.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS);
    }

    public static void setDateFormat(DateFormat dateFormat){
        mapper.setDateFormat(dateFormat);
    }

    /**
     * 把java对象转为JSON字符串
     * @param obj
     * @return
     */
    public static String toJson(Object obj){
        try {
            return mapper.writeValueAsString(obj);
        } catch (IOException e) {
            LOG.error("to json exception.",e);
            throw new JSONException("把对象转换为JSON时出错了",e);
        }
    }

}

final class JSONException extends RuntimeException{
    public JSONException(final String message) {
        super(message);
    }

    public JSONException(final String message,final Throwable cause) {
        super(message, cause);
    }
}